package com.marion.codestandard.demo009.rpc;

import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author Marion
 * @date 2022/5/13 17:41
 */
@Service
public class ShopService {

    /**
     * v1: 串行执行
     */
    public void goods() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        System.out.println(userInfo());
        System.out.println(goodsInfo());
        System.out.println(commentInfo());

        stopWatch.stop();
        System.out.println("[goods] execute time=" + stopWatch.getTotalTimeMillis() + "ms");
    }

    public void syncGoods() throws ExecutionException, InterruptedException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        CompletableFuture<String> s1 = CompletableFuture.supplyAsync(this::userInfo);
        CompletableFuture<String> s2 = CompletableFuture.supplyAsync(this::goodsInfo);
        CompletableFuture<String> s3 = CompletableFuture.supplyAsync(this::commentInfo);

        CompletableFuture<Object> objectCompletableFuture = s1.thenCombine(s2, (o1, o2) -> o1 + ":" + o2)
                .thenCombine(s3, (o1, o2) -> o1 + ":" + o2);
        String ret = (String) objectCompletableFuture.get();
        System.out.println(ret);

        stopWatch.stop();
        System.out.println("[goods] execute time=" + stopWatch.getTotalTimeMillis() + "ms");
    }

    public String userInfo() {
        try {
            Thread.sleep(200L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "userInfo";
    }

    public String goodsInfo() {
        try {
            Thread.sleep(200L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "goods";
    }

    public String commentInfo() {
        try {
            Thread.sleep(200L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "commentInfo";
    }
}
